package com.szjlxh.data.repository;

import com.szjlxh.data.entity.HourForcastBean;
import com.szjlxh.data.entity.HoursWeatherLastBean;
import com.szjlxh.data.entity.StationNameBean;
import com.szjlxh.data.entity.SunDataBean;
import com.szjlxh.data.entity.WeatherBaseBean;
import com.szjlxh.data.entity.WeatherSevenDayBean;
import com.szjlxh.data.net.ApiConnection;
import com.szjlxh.data.net.BaseWeatherInfoApi;
import com.szjlxh.data.net.BaseWeatherInfoApiImpl;
import com.szjlxh.data.net.ConstantUrl;
import com.szjlxh.data.utils.Constants;
import com.szjlxh.data.utils.DataUtils;
import com.szjlxh.data.utils.GsonObjectFormatter;
import com.szjlxh.domain.model.SunInfo;
import com.szjlxh.domain.model.index.Station;
import com.szjlxh.domain.model.index.WeatherBaseData;
import com.szjlxh.domain.model.index.WeatherHourData;
import com.szjlxh.domain.model.index.WeatherSevenDay;
import com.szjlxh.domain.repository.IBaseWeatherRespository;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by liutao on 16/3/18.
 */
@Singleton
public class BaseWeatherRepository implements IBaseWeatherRespository {

    @Inject
    public BaseWeatherRepository() {

    }

    @Override
    public Observable<SunInfo> sunInfo() {
        BaseWeatherInfoApi api = new BaseWeatherInfoApiImpl();
        return api.sunDownRiseInfo().map(new Func1<SunDataBean, SunInfo>() {
            @Override
            public SunInfo call(SunDataBean sunDataBean) {
                SunInfo sunInfo = new SunInfo();
                sunInfo.setDowndownTime(sunDataBean.getSundata().getSunset());
                sunInfo.setDownriseTime(sunDataBean.getSundata().getSunrise());
                return sunInfo;
            }
        });
    }

    @Override
    public Observable<List<WeatherSevenDay>> weatherSevenDay() {
        return Observable.create(new Observable.OnSubscribe<WeatherSevenDayBean>() {
            @Override
            public void call(Subscriber<? super WeatherSevenDayBean> subscriber) {
                try {
                    String resString = ApiConnection.createGET(ConstantUrl.SEVEN_DAY_WEATHER_URL).requestSyncCall();
                    subscriber.onNext(new GsonObjectFormatter<WeatherSevenDayBean>(resString).getObjectFromType(WeatherSevenDayBean.class));
                } catch (Exception e) {
                    subscriber.onError(e.getCause());
                }
            }
        }).map(new Func1<WeatherSevenDayBean, List<WeatherSevenDay>>() {
            @Override
            public List<WeatherSevenDay> call(WeatherSevenDayBean weatherSevenDayBean) {
                List<WeatherSevenDay> weatherSevenDays = new ArrayList<>();
                for (int i = 0; i < weatherSevenDayBean.getData().size(); i++) {
                    WeatherSevenDayBean.DataEntity content = weatherSevenDayBean.getData().get(i);
                    WeatherSevenDay temp = new WeatherSevenDay();
//                    temp.setResId(content.getWeather());
                    temp.setIconLastName(content.getWeatherICON());
                    temp.setWeekDay(content.getWeekday());
                    temp.setMonthDay(content.getMonthday());
                    temp.setMaxTemp(Integer.valueOf(content.getTempMax()));
                    temp.setMingTemp(Integer.valueOf(content.getTempMin()));
                    temp.setWeatherName(content.getWeather());
                    temp.setWindName(content.getWindB());
                    temp.setWindScale(content.getWind());
                    weatherSevenDays.add(temp);
                }

                return weatherSevenDays;
            }
        });
    }

//    public String getWeekDay() {
//        if (Date==null) return "星期X";
//        Pattern pattern = Pattern.compile("(-?[1-9]\\d*)");
//        Matcher matcher = pattern.matcher(getDate());
//        if (matcher.find()) {
//            return DataUtils.getWeekOfDate(Long.valueOf(matcher.group(1)));
//        } else {
//            return "星期X";
//        }
//    }

    @Override
    public Observable<WeatherBaseData> weatherBaseData() {
        return Observable.create(new Observable.OnSubscribe<WeatherBaseBean>() {
            @Override
            public void call(Subscriber<? super WeatherBaseBean> subscriber) {
                try {
                    String resString = ApiConnection.createGET(ConstantUrl.WEATHER_BASE_DATA_URL).requestSyncCall();
                    subscriber.onNext(new GsonObjectFormatter<WeatherBaseBean>(resString).getObjectFromType(WeatherBaseBean.class));
                } catch (Exception e) {
                    subscriber.onError(e.getCause());
                }
            }
        }).map(new Func1<WeatherBaseBean, WeatherBaseData>() {
            @Override
            public WeatherBaseData call(WeatherBaseBean weatherBaseBean) {
                WeatherBaseData data = new WeatherBaseData();
                WeatherBaseBean.ResultEntity content = weatherBaseBean.getResult().get(0);
                float tempF = Float.valueOf(content.getTEMP());
                int tempI = (int) tempF;
                data.setTemp(tempI + "");
                String weather = Constants.getWeatherData().get(content.getWEATHERCODE());
                if (weather == null)
                    data.setWeatherName(content.getWEATHERCODE());
                else
                    data.setWeatherName(weather);
                data.setWindDirection(content.getWIND_DIRECTIONNAME());
                data.setHumidity(content.getHUMIDITY() + Constants.UNIT_HUMIDITY);
                data.setFeelingTemp(content.getFEELTEMP() + Constants.UNIT_DEGREE);
                data.setPm25(content.getPM25());
                data.setVisibility(content.getFormatVisibility());
                data.setUpdateDate(content.getFormatUpdateDate());
                data.setCurrentDate(DataUtils.getDate());
                return data;
            }
        });
    }

    @Override
    public Observable<List<WeatherHourData>> weatherLastHourData() {
        return Observable.create(new Observable.OnSubscribe<HoursWeatherLastBean>() {
            @Override
            public void call(Subscriber<? super HoursWeatherLastBean> subscriber) {
                try {
                    String resString = ApiConnection.createGET(ConstantUrl.LAST_24_HOURS_URL).requestSyncCall();
                    subscriber.onNext(new GsonObjectFormatter<HoursWeatherLastBean>(resString).getObjectFromType(HoursWeatherLastBean.class));
                } catch (Exception e) {
                    subscriber.onError(e.getCause());
                }
            }
        }).map(new Func1<HoursWeatherLastBean, List<WeatherHourData>>() {
            @Override
            public List<WeatherHourData> call(HoursWeatherLastBean hoursWeatherLastBean) {
                List<WeatherHourData> data = new ArrayList<>();
                for (int i = 0; i < hoursWeatherLastBean.getResult().size(); i++) {
                    HoursWeatherLastBean.ResultEntity content = hoursWeatherLastBean.getResult().get(i);
                    WeatherHourData temp = new WeatherHourData();
                    temp.setWeatherResString(content.getWEATHER());
                    temp.setHour(DataUtils.getFormatHour(content.getBJ_DATETIME()));
                    temp.setWeatherName(Constants.getWeatherData().get(content.getWEATHER()));
                    temp.setTemp(content.getTEMP() + Constants.UNIT_DEGREE);
                    temp.setWindName(content.getWIND_DIRECTIONNAME());
                    temp.setWindScale(content.getWIND_SCALE() + Constants.UNIT_LEVEL);
                    temp.setRainAmount(content.getHOUR_RAIN() + Constants.UNIT_RAIN);
                    data.add(temp);
                }
                return data;
            }
        });
    }

    @Override
    public Observable<List<WeatherHourData>> weatherFutureHourData() {
        return Observable.create(new Observable.OnSubscribe<HourForcastBean>() {
            @Override
            public void call(Subscriber<? super HourForcastBean> subscriber) {
                try {
                    String resString = ApiConnection.createGET(ConstantUrl.FUTURE_24_HOURS_URL).requestSyncCall();
                    subscriber.onNext(new GsonObjectFormatter<HourForcastBean>(resString).getObjectFromType(HourForcastBean.class));
                } catch (Exception e) {
                    subscriber.onError(e.getCause());
                }
            }
        }).map(new Func1<HourForcastBean, List<WeatherHourData>>() {
            @Override
            public List<WeatherHourData> call(HourForcastBean hourForcastBean) {
                List<WeatherHourData> data = new ArrayList<>();
                for (int i = 0; i < hourForcastBean.getWEATHERDATA().size(); i++) {
                    HourForcastBean.WEATHERDATAEntity content = hourForcastBean.getWEATHERDATA().get(i);
                    WeatherHourData temp = new WeatherHourData();
//                    temp.setHour("Z时");
                    temp.setWeatherResString(content.getWEATHER());
                    temp.setHour(DataUtils.getFormatHour(content.getBJ_DATETIME()));
                    temp.setWeatherName(content.getWEATHERNAME());
                    temp.setTemp(content.getTEMP() + Constants.UNIT_DEGREE);
                    temp.setWindName(content.getWIND_DICRECTNAME() + Constants.UNIT_WIND);
                    temp.setWindScale(content.getWIND_SCALE() + Constants.UNIT_LEVEL);
                    temp.setRainAmount(content.getHOURS_RAIN() + Constants.UNIT_RAIN);
                    data.add(temp);
                }
                return data;
            }
        });
    }

    @Override
    public Observable<Station> getStationName(final String lng, final String lat) {
        return Observable.create(new Observable.OnSubscribe<StationNameBean>() {
            @Override
            public void call(Subscriber<? super StationNameBean> subscriber) {
                try {
                    String resString = ApiConnection.createGET(ConstantUrl.REQUEST_STATION_NAME_URL + "?lng=" + lng + "&lat=" + lat).requestSyncCall();
                    subscriber.onNext(new GsonObjectFormatter<StationNameBean>(resString).getObjectFromType(StationNameBean.class));
                } catch (Exception e) {
                    subscriber.onError(e.getCause());
                }
            }
        }).map(new Func1<StationNameBean, Station>() {
            @Override
            public Station call(StationNameBean stationNameBean) {
                Station station = new Station();
                station.setId(stationNameBean.getStationID());
                station.setName(stationNameBean.getStationName());
                return station;
            }
        });
    }


}
